<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

require 'Libs/mail/PHPMailerAutoload.php';

class Mail {

    public static $instance;
    public $mail;
    public $html;
    public $body;
    public $config = array(
        'username' => 'pulse@buzzmetrics.vn',
        'password' => 'L7-jc!JAz1b1i r',
        'fromname' => 'BuzzPulse',
    );

    public function __construct() {
        //allocate your stuff
    }

    public function __get($name) {
        return $this->$name;
    }

    public function __set($name, $value) {
        $this->$name = $value;
    }

    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public static function withMailInfo($username, $password, $fromname) {
        $this->config['username'] = $username;
        $this->config['password'] = $password;
        $this->config['fromname'] = $fromname;
    }

    public static function sendTeam($userid, $streamid) {
        $db = Database::getInstance();
        $query = "SELECT email FROM users WHERE teamid = (SELECT teamid FROM users WHERE userid = '$userid')";
        $emailresult = $db->query($query);
        if ($emailresult->returnCode == 200) {
            if ($emailresult->dataTable->numOfRow > 0) {
                foreach ($emailresult->dataTable->rows as $row) {
                    $subject = "Team BuzzPulse";
                    $mail = self::withData($row["email"], $subject);
                    $mail->send($streamid);
                }
            }
        }
    }

    public static function shareEmail($sendTo, $subject, $content) {
        $instance = self::getInstance();
        date_default_timezone_set('Etc/UTC');
        $mail = new PHPMailer();
        $mail->isSMTP();
        //Enable SMTP debugging
        // 0 = off (for production use)
        // 1 = client messages
        // 2 = client and server messages
        $mail->CharSet = "UTF-8";
        $mail->SMTPDebug = 0;
        $mail->Debugoutput = 'html';
        $mail->Host = "smtp.gmail.com";
        $mail->Port = 465;
        $mail->SMTPSecure = 'ssl';
        $mail->SMTPAuth = true;
        $mail->Username = $instance->config['username'];
        $mail->Password = $instance->config['password'];
        $user = User::getLogedInUser();
        $nameFrom = $instance->config['fromname'];
        $mailFrom = $instance->config['username'];
        $mail->setFrom($mailFrom, $nameFrom);
        $mailTo = explode(';', $sendTo);
        foreach ($mailTo as $maild) {
            $mailData = explode('|', $maild);
            $mail->addAddress($mailData[1], $mailData[0]);
        }
        $mail->Subject = ($subject);
        $mail->AltBody = "";
        $mail->Body = "";
        $mail->msgHTML($content);
        if ($mail->send()) {
            return "done";
        } else {
            return $mail->ErrorInfo;
        }
    }

    public static function send($sendTo, $subject, $content) {
        $instance = self::getInstance();
        date_default_timezone_set('Etc/UTC');
        $mail = new PHPMailer();
        $mail->isSMTP();
        //Enable SMTP debugging
        // 0 = off (for production use)
        // 1 = client messages
        // 2 = client and server messages
        $mail->CharSet = "UTF-8";
        $mail->SMTPDebug = 0;
        $mail->Debugoutput = 'html';
        $mail->Host = "smtp.gmail.com";
        $mail->Port = 465;
        $mail->SMTPSecure = 'ssl';
        $mail->SMTPAuth = true;
        $mail->Username = $instance->config['username'];
        $mail->Password = $instance->config['password'];
        $user = User::getLogedInUser();
        $nameFrom = $instance->config['fromname'];
        $mailFrom = $instance->config['username'];
        $mail->setFrom($mailFrom, $nameFrom);
        $mailTo = $sendTo;
        if (strpos($sendTo, ';')) {
            $mailTo = explode(';', $sendTo);
        }
        if (is_array($mailTo)) {
            foreach ($mailTo as $maild) {
                $mailData = explode('|', $maild);
                $mail->addAddress($mailData[1], $mailData[0]);
            }
        } else {
            $mailData = explode('|', $mailTo);
            $mail->addAddress($mailData[1], $mailData[0]);
        }
        $mail->Subject = $subject;
        $mail->AltBody = "";
        $mail->Body = "";
        $mail->msgHTML($content);
        if ($mail->send()) {
            return "done";
        } else {
            return $mail->ErrorInfo;
        }
    }

    public static function getTemplate($id) {
        $result = Database::getInstance()->query("SELECT * FROM templates WHERE id='$id'");
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $row = $result->dataTable->rows[0];
                return $row;
            }
        }
    }

    public static function buildHTMLSinglePost($content, $reply, $data, $streamID) {
        $template = self::getTemplate(1);
        $mainData = $template['maindata']; //template of thread on database
        $subData = $template['subdata']; //template of replies on database
        //get replies HTML from template
        $replies = json_decode($reply);
        $repliesHTML = '';
        for ($i = 0; $i < sizeof($replies); $i++) {
            $contenttmp = str_replace("Show less", "", str_replace("...Read more", "", $replies[$i]->content));
            $old = array("{avatar}", "{replyContent}", "{replyTime}", "{numOfLikes}");
            $new = array($replies[$i]->avatar, self::cutString($contenttmp), $replies[$i]->time, trim($replies[$i]->likes));
            $repliesHTML = $repliesHTML . str_replace($old, $new, $subData);
        }

        //get thread HTML from template
        $threadData = json_decode($data); //object(img , time , threadTitle , icon , source , streamTitle , text)
        if ($threadData->img != null) {
            $img = $img . '<div style="width:80px;min-height:80px;overflow:hidden;padding-top:5px;padding-right:10px;float:left">'
                    . '<img src="' . $threadData->img . '" width="100%"></div>'
                    . '<div style="padding-left:85px; padding-top: 5px;">'
                    . self::cutString($threadData->text) . '</div>';
        } else {
            $img = $img . '<div style="padding-left:0px; padding-top: 5px;">' . self::cutString($threadData->text) . '</div>';
        }
        $old = array('{threadTime}', '{threadTitle}', '{sourceIcon}', '{threadSource}', '{streamLink}', '{author}', '{threadImage}', '{sendTime}', '{content}', '{subData}');
        $new = array($threadData->time, $threadData->threadTitle, $threadData->icon, $threadData->source, $_SERVER["HTTP_HOST"] . '/#stream/' . base64_encode($streamID), $threadData->author, $img, self::formatDate(getdate()), $content, $repliesHTML);
        $threadHTML = $threadHTML . str_replace($old, $new, $mainData);

        return $threadHTML;
    }

    public static function sendDigestEmail($debug) {
        $debug = true;
        $filter = array('sentiment' => 3);
        $email_options = Options::getAllUserOptions('subscribed_streams', "array", '{"value": "!"}');
        $tempdata = array();
        foreach ($email_options as $options) {
            $user = User::withId($options->userId);
            $email = $user->fullname . '|' . $user->email;
            $date = new DateTime();
            $dateText = $date->format('M d');
            foreach ($options->value as $streamId) {
                $content = Mail::dailyDigestHTML($streamId, $filter);
                $stream = Stream::withId($streamId);
                if ($content != null) {
                    echo 'sending to ' . $email . '<br>';
                    $mentions = $content['mentions'];
                    echo "<h2>Summary of buzz on $dateText for Stream $stream->name</h2>";
                    echo $content['text'];
                    if (!$debug)
                        echo '<h2>' . self::send($email, "Summary of buzz on $dateText for Stream $stream->name", $content['text']) . '</h2>';
                }
                echo '<br>';
            }
        }
    }

    public static function processPulse($pulse) {
        foreach ($pulse as $message) { //process replies
            $threadId = $message->getThreadId();
            //Load total replies
            $date = new DateTime($startDate);
            $messageId = $message->getId();
            if ($tag != 0 || $sentiment != 0) {
                $text = $message->getText();
                $lead = $message->getLead();
                $replyDate = DateTime::createFromFormat("Y-m-d H:i:s", $message->getTime());
                $text = str_replace("\n", "<br>", $text);

                $reply['text'] = Signal::removeLinkForEmail($text);
                $reply['time'] = $replyDate;
                $reply['author'] = $message->getAuthor();
                $reply['authorUrl'] = $message->getAuthorUrl();
                $reply['messageId'] = $message->getId();
                $reply['threadId'] = $message->getThreadId();
                $reply['numberOfLikes'] = $message->getNumberOfLikes();
                if ($message->getSource() == 'plus.google.com') {
                    $urlParams = explode('/', $message->getURL());
                    $reply['guserid'] = $urlParams[3];
                }

                if ($message->getSource() == 'www.facebook.com') {
                    $postParams = explode('/', $message->getURL());
                    $postData = $postParams[5];
                    $data = explode('?comment_id=', $postData);
                    $reply['fbUserId'] = $postParams[3];
                    $reply['fbPostId'] = $data[0];
                    if (count($data) > 1)
                        $reply['fbCommentId'] = $data[1];
                    else
                        $reply['fbCommentId'] = '';
                    //$reply['fbObjectId'] = Facebook::getFacebookObjectId($reply['fbUserId'], $reply['fbPostId']);
                }
                //$tempdata[$threadId]["replies"] = array();
                if (strlen($message->getText()) != strlen($message->getLead()))
                    $tempdata[$threadId]["replies"][] = $reply;
                $tempdata[$threadId]["message"] = $message;
                $tempdata[$threadId]["type"] = $message->getType();
            } else {
                if ($messageAction == null)
                    $messageAction = '';
                $text = $message->getText();
                $lead = $message->getLead();
                $replyDate = DateTime::createFromFormat("Y-m-d H:i:s", $message->getTime());
                $text = str_replace("\n", "<br>", $text);

                $reply['text'] = Signal::removeLinkForEmail($text);
                $reply['time'] = $replyDate;
                $reply['author'] = $message->getAuthor();
                $reply['authorUrl'] = $message->getAuthorUrl();
                $reply['messageId'] = $message->getId();
                $reply['threadId'] = $message->getThreadId();
                $reply['numberOfLikes'] = $message->getNumberOfLikes();

                if (strlen($message->getText()) != strlen($message->getLead()))
                    $tempdata[$threadId]["replies"][] = $reply;
                $tempdata[$threadId]["message"] = $message;
                $tempdata[$threadId]["type"] = $message->getType();
            }
        }
        foreach ($tempdata as $key => $value) {
            $signal = Signal::withItem($value["message"], new Stream());
            $signal->leadData = $value;
            $signal->type = $value["type"];
            $message = $value["message"];
            $signal->totalReplies = $message->totalReplies;
            if (!$signal->totalReplies) {
                $signal->totalReplies = count($value['replies']);
            }
            $signal->isRead = $message->isRead;
            //$signalController->save
            $signals[] = $signal;
        }
        return $signals;
    }

    public static function findMaxPulse(&$signals, $value = 1) {
        if (count($signals) == 0)
            return false;
        $maxI = 0;
        $maxReplies = $signals[0]->message->replyCount[$value];
        if ($value == 0)
            $maxReplies = $signals[0]->message->totalReplies;
        $curPulse = $signals[0];
        for ($i = 0; $i < count($signals); $i++) {
            $signal = $signals[$i];
            $replies = $signal->message->replyCount[$value];
            if ($value == 0)
                $replies = $signals[$i]->message->totalReplies;
            if ($maxReplies < $replies) {
                $curPulse = $signal;
                $maxReplies = $replies;
                $maxI = $i;
            }
        }
        if (count($signals) == 0)
            return NULL;
        unset($signals[$maxI]);
        return $curPulse;
    }

    public static function sortPulse(&$signals, $value = 1) {
        if (count($signals) == 1)
            return $signals;
        $sortedPulse = array();
        $maxPulse = self::findMaxPulse($signals, $value);
        while ($maxPulse !== null) {
            $sortedPulse[] = $maxPulse;
            $maxPulse = self::findMaxPulse($signals, $value);
        }
        return $sortedPulse;
    }

    public static function dailyDigestHTML($streamId, $_filter) {
        $date = new DateTime("01-05-2014");
        $tagId = array_key_exists('tagid', $_filter) ? $_filter['tagid'] : array('0');
        $sentiment = array_key_exists('sentiment', $_filter) ? $_filter['sentiment'] : 0;
        $source = array_key_exists('source', $_filter) ? $_filter['source'] : array('0');
        $type = array_key_exists('type', $_filter) ? $_filter['type'] : array('0');
        $stream = Stream::withId($streamId);
        $dateText = $date->format('Y-m-d');
        $pulses = self::processPulse(Stream::getPulse($stream->streamId, $dateText, $dateText, 0, 10, array(0), array(0), array(0), array(-1, 1, 0)));
        if (count($pulses) == 0)
            return null;
        $pulsePositiveOrder = self::sortPulse($pulses, 1);
        $pulseNegativeOrder = self::sortPulse($pulses, -1);
        $pulseAllOrder = self::sortPulse($pulses, 0);
        $emailHTML = '<p>There are '.$pulseAllOrder[0]->message->totalMessages.' mentions for today, generated by '.$pulseAllOrder[0]->message->numberOfThreads.' threads.</p>';
        $emailHTML .= '<br>Breakdown of today sentiment:<br>';
        $_filter = array();
        $_filter['streamId'] = 'MTQw';
        $_filter['dateFrom'] = $dateText;
        $_filter['dateTo'] = $dateText;
        $_filter['source'] = array('0');
        $_filter['type'] = array('0');
        $_filter['tags'] = array('0');
        $sovChart = Metrics::getChartPNG(Metrics::generateSentimentAggregatesChart($_filter), '400px');
        Metrics::generateFunctionalSentimentChart($_filter);
        $emailHTML .= '<img src="data:image/png;base64,'.$sovChart.'"/>';
        $mentions = 0;
        $time = new DateTime();
        foreach ($pulsePositiveOrder as $pulse) {
            $threadContent = ltrim(Signal::removeLinkForEmail($pulse->message->getLead() . ' '), '​ ');
            $time = new DateTime($pulse->message->getTime());
            $negativeMention = $pulse->message->totalReplies . ' positive mentions';
            if ($pulse->message->totalReplies < 5)
                continue;
            $mentions += $pulse->message->totalReplies;
            $emailHTML .= '<div><p><a href="' . $pulse->message->getURL() . '"><strong>' . $pulse->message->getThreadTitle() . '</strong> (' . $negativeMention . ')<br></a>';
            $shortContent = substr($threadContent, 0, strpos($threadContent, ' ', 100));
            if ($shortContent == '')
                $shortContent = $threadContent;
            $emailHTML .= $shortContent . '... <br>';
            //var_dump($pulse->leadData['replies]']);
            $maxReplies = (2 < $pulse->message->totalReplies) ? 2 : $pulse->message->totalReplies;
            for ($i = 0; $i < $maxReplies; $i++) {
                $reply = $pulse->leadData['replies'][$i];
                $replyText = Signal::removeLinkForEmail($reply['text']);
                $shortReply = substr($replyText, 0, strpos($replyText, ' ', 100));
                if ($shortReply == '')
                    $shortReply = $replyText;
                $replyTime = '';
                if ($reply['time'] !== null)
                    $replyTime = $reply['time']->format('d-m-Y H:s:i');
                $emailHTML .= '<blockquote style="border-left: 1px solid gray; margin: 5px 0px 10px 20px; padding-left: 10px;"><strong>' . $reply['author'] . '</strong>: ' . $shortReply . '...<br><em>on ' . $replyTime . '</em></blockquote><br>';
            }
            $emailHTML .= '<em>' . $time->format('M d Y \a\t H:i:s') . '</em></p></div>';
        }
        return array('mentions' => $mentions,
            'text' => $emailHTML . '<p>Buzzmetrics Team</p>'
            . '<p>You have subscribed to Buzzmetrics real-time social media monitoring and alert. To turn this alert off, please login to your account at http://pulse.buzzmetrics.vn or contact your account manager for support.</p>');
    }

    public static function withData($to, $subject, $reply = NULL, $attachpath = NULL, $body = NULL) {
        $instance = self::getInstance();
        date_default_timezone_set('Etc/UTC');
        $mail = new PHPMailer();
        $mail->isSMTP();
        //Enable SMTP debugging
        // 0 = off (for production use)
        // 1 = client messages
        // 2 = client and server messages
        $mail->SMTPDebug = 0;
        $mail->Debugoutput = 'html';
        $mail->Host = "smtp.gmail.com";
        $mail->Port = 587;
        $mail->SMTPSecure = 'tls';
        $mail->SMTPAuth = true;
        $mail->Username = $instance->config["username"];
        $mail->Password = $instance->config["password"];
        $mail->setFrom($instance->config["username"], $instance->config["fromname"]);
        if ($reply)
            $mail->addReplyTo($reply, $reply);
        else
            $mail->addReplyTo($instance->config["username"], $instance->config["username"]);
        $mail->addAddress($to, $to);
        $mail->Subject = $subject;
        $mail->AltBody = "";
        if ($body)
            $mail->Body = $body;
        if ($attachpath)
            $mail->addAttachment($attachpath);
        $instance->mail = $mail;
        return $instance;
    }

    public static function getHost($mail) {
        $pieces = explode("@", $mail);
        $host = explode(".", $pieces[1]);
        switch ($host[0]) {
            case "gmail":
                return "smtp.gmail.com";
            case "yahoo":
                return "smtp.mail.yahoo.com";
            case "outlook":
                return "smtp.live.com";
            case "msn":
                return "smtp.email.msn.com";
            case "lycos":
                return "smtp.mail.lycos.com";
            case "aol":
                return "smtp.aol.com";
        }
    }

    /* public function send($streamid) {
      $stream = Stream::withId($streamid);
      $time = new DateTime();
      $datetime = $time->format("Y-m-d");
      $timezone = 7;
      $query = $stream->query;
      $language = $stream->language;
      $length = 4;
      $zMessage = new ZMessageReader($datetime . ' 00:00:00', $datetime . ' 23:59:59', $timezone, $query, $language, 0, $length);
      $collection = $zMessage->read();
      if (sizeof($collection) > 0) {
      $div = "";
      foreach ($collection->getItems() as $message) {
      $signal = Signal::withItem($message, Stream::withId($streamid));
      $temp = '<div style = "display: block;position: relative;width: 100%;float: none;">
      <div style = "display: block;padding: 0 0 0 20px;position: relative;">
      <div style = "display: block;width: 100%;float: left;position: relative;">
      <div style = "display: block;margin-right: 20px;position: relative;">
      <div style = "border-top: 1px solid #dddddd; display: block;position: relative;box-shadow: 1px 1px 0px 0 #cecece, -1px 1px 0px 0 #cecece;-moz-box-shadow: 1px 1px 0px 0 #cecece, -1px 1px 0px 0 #cecece;-webkit-box-shadow: 1px 1px 0px 0 #cecece, -1px 1px 0px 0 #cecece;background: #fff;margin-left: 0;">
      <div style = "style="display:block;
      padding:5px 12px 36px 5px;
      border-top:none;
      min-height:75px">
      <div style="display: block;
      height: 65px;
      ">
      <div style="margin-right:5px;
      display:block;
      float:left;
      border-right-width:11px;
      margin-top: 5px;
      margin-left: 5px;
      margin-bottom: 5px;
      ">
      <a href="' . $message->getURL() . '" style="text-decoration: none;
      cursor: pointer;
      " target="_blank">
      <img src="' . $signal->image . '" style="margin-top: 0px;
      width: 100px;
      height: auto;
      border: 0;
      -ms-interpolation-mode: bicubic;
      vertical-align: middle;
      max-width: 260px;
      -webkit-transition: opacity 0.20s linear;
      -moz-transition: opacity 0.15s linear;
      -ms-transition: opacity 0.15s linear;
      -o-transition: opacity 0.15s linear;
      transition: opacity 0.15s linear;
      opacity: 0.9;
      filter: alpha(opacity = 90);
      "></a>
      </div>
      <div style=
      "display: block;
      overflow: hidden;
      margin-left: 0;
      min-height: 50px;
      ">
      <div style="display: block;
      padding: 0;
      margin-top: 5px;
      ">
      <p style="float: left;
      margin: 0;
      padding: 0;
      display: block;
      -webkit-margin-before: 1em;
      -webkit-margin-after: 1em;
      -webkit-margin-start: 0px;
      -webkit-margin-end: 0px;
      ">
      <a href="' . $message->getURL() . '"
      style="text-decoration: none;
      cursor: pointer;
      color: #333;font-weight: 700;line-height: 15px;font-size: 15px;"
      target = "_blank">' . $message->getThreadTitle() . '</a></p>
      <p style = "color:#a4a4a4;font-size:11px;line-height:12px;text-align:right; margin-right: 15px; margin-bottom: 0px;margin-top: 0px;">
      ' . $signal->date->format("Y-m-d") . '</p>
      <p style = "width: 100%; float: left; margin: 0;padding: 0;display: block;-webkit-margin-before: 1em;-webkit-margin-after: 1em;-webkit-margin-start: 0px;-webkit-margin-end: 0px;">
      <a href = "' . $message->getURL() . '" style = "text-decoration: none;cursor: pointer;font-size: 11px;line-height: 15px;color: #00a245;-ms-word-break: break-all;word-break: break-all;"
      target = "_blank">' . $message->getSource() . '</a><a href = "' . $message->getURL() . '"
      style = "margin-left: 5px;padding-left: 5px;border-left: 1px solid orange;text-decoration: none;cursor: pointer;font-size: 11px;line-height: 15px;color: #00a245;-ms-word-break: break-all;word-break: break-all;"
      target = "_blank">' . $message->getAuthor() . '</a></p>
      </div>
      <p style = "margin: 0; margin-right:20px; padding: 10px 0 0 0;display: block;-webkit-margin-before: 1em;-webkit-margin-after: 1em;-webkit-margin-start: 0px;-webkit-margin-end: 0px;line-height: 18px;font-size: 12px;color: #333;word-wrap: break-word;">
      ' . $signal->mailText . '<span class = "readmore-threedot" style = "font-family: Calibri;">...</span></p>
      </div></div></div></div></div></div>
      <div style = "display: block;clear: both;font-size: 0px;line-height: 0px;height: 0px;">
      </div>
      </div>
      </div>';
      $div = $div . $temp;
      }
      $timesend = getdate();
      $html = '<!DOCTYPE html>
      <html style = "font-size: 100%;">
      <head>
      <meta content = "text/html; charset=utf-8" http-equiv = "Content-Type">
      <title>BuzzPulse Notifications</title>
      </head>
      <body style = "font-family: Calibri, sans-serif;font-size: 13px; padding-top: 16px;">
      <table border = "0" cellpadding = "0" cellspacing = "0" style = "table-layout:fixed;font-family:arial;font-size:0px;line-height:0px" width = "100%">
      <tbody>
      <tr style = "background-color: #F0F0F0">
      <td height = "10" width = "450"><img height = "1" width = "450"></td>
      <td width = "150"><img height = "1" width = "150"></td>
      </tr>
      <tr style = "background-color: #F0F0F0">
      <td align = "left" valign = "bottom">
      <div>
      <table border = "0" cellpadding = "0" cellspacing = "0"
      style = "table-layout:fixed;font-family:arial;font-size:0px;line-height:0px; padding-left: 20px;"
      width = "450">
      <tbody>
      <tr>
      <td><span style = "font-size:10px;line-height:12px;color:#bababa">
      <span class = "il">BuzzPulse</span> Mentions
      Alerts for your company, competitors and
      market</span></td>
      </tr>
      </tbody>
      </table><br>
      <img height = "7" width = "1"><br>
      </div>
      <table border = "0" cellpadding = "0" cellspacing = "0" style = "table-layout:fixed;font-family:arial;font-size:0px;line-height:0px; padding-left: 20px;"
      width = "450">
      <tbody>
      <tr>
      <td style = "color: #40bfff; font-size: 25px; font-weight: bold; line-height: 27px">
      ' . self::formatDate($timesend) . '</td>
      </tr>
      </tbody>
      </table>
      </td>
      <td align = "right" valign = "bottom">
      </td>
      </tr>
      <tr style = "background-color: #F0F0F0">
      <td colspan = "2" height = "10"></td>
      </tr>
      </tbody>
      </table>
      <div style = "color: #333333; background-color: #f0f0f0;">
      <table border = "0" cellpadding = "0" cellspacing = "0" style = "table-layout:fixed;font-family:arial;font-size:0px;line-height:0px;padding-right: 20px;padding-left: 20px;"
      width = "100%">
      <tbody style = "display: table-row-group; vertical-align: middle; border-color: inherit; font-family: arial; font-size: 0px; line-height: 0px;">
      <tr style = "background-color: #999999">
      <td height = "30" width = "20"><img height = "1" width = "20"></td>
      <td align = "left" valign = "middle" width = "280"><img height = "1"
      width = "280"><br>
      <span style = "color:#f2f2f6;font-size:14px;line-height:16px">' . strtoupper($stream->name) . '</span></td>
      <td align = "right" valign = "middle" width = "280"><img height = "1"
      width = "280"></td>
      <td width = "20"><img height = "1" width = "20"></td>
      </tr>
      </tbody>
      </table>
      ' . $div . '
      <div style = "padding-left: 20px; padding-right: 20px; padding-bottom: 10px;">
      <table width = 100% cellpadding = "0" cellspacing = "0" border = "0" style = "table-layout:fixed;font-family:arial;font-size:0px;line-height:0px">
      <tbody><tr bgcolor = "#ffffff">
      <td width = "20"><img width = "20" height = "1"></td>
      <td align = "left" width = "560" height = "25" valign = "top">
      <a href = "' . $_SERVER["HTTP_HOST"] . '/#stream/' . $streamid . '" style = "font-size:11px;line-height:14px;color:#007fb8;text-decoration:none" target = "_blank">
      MORE MENTIONS ABOUT ' . strtoupper($stream->name) . '</a>
      </td>
      </tr>
      </tbody></table>
      <table width = 100% cellpadding = "0" cellspacing = "0" border = "0" style = "table-layout:fixed;font-size:0px;line-height:0px">
      <tbody><tr bgcolor = "#ffffff"><td height = "10"></td></tr>
      <tr bgcolor = "#999999"><td height = "5"></td></tr>
      </tbody></table></div>
      </div>
      </body>
      </html>';
      $this->mail->msgHTML($html, dirname(__FILE__));
      if (!$this->mail->send()) {
      echo "Mailer Error: " . $this->mail->ErrorInfo;
      } else {
      echo "Message sent!";
      }
      }
      } */

    public static function formatDate($datetime) {
        if ($datetime["hours"] < 12) {
            $time = $datetime["weekday"] . ', ' . substr($datetime["month"], 0, 3) . ' ' . substr($datetime["mday"], 0, 3) . ', ' . $datetime["hours"] . ':' . $datetime["minutes"] . ' AM UTC';
        } else {
            $time = $datetime["weekday"] . ', ' . substr($datetime["month"], 0, 3) . ' ' . substr($datetime["mday"], 0, 3) . ', ' . ($datetime["hours"] - 12) . ':' . $datetime["minutes"] . ' PM UTC';
        }
        return $time;
    }

    public static function cutString($string) {
        if (strlen($string) > 200) {
            // truncate string
            $stringCut = substr($string, 0, 200);
            // make sure it ends in a word so assassinate doesn't become ass...
            $string = substr($stringCut, 0, strrpos($stringCut, ' ')) . '... <a href="">Read More</a>';
        }
        return $string;
    }

}
?>
